<?php
/**
 * 用户信息
**/
include("../includes/common.php");
$title='用户信息';
if($conf['forcelogin']==1 && !$islogin2) {loginsmsg('请登录后再操作！');}

// 统计数据
$today0 = date("Y-m-d 00:00:00");
$total_files = intval($DB->getColumn("SELECT count(*) FROM pre_file WHERE uid='{$uid}'"));
$today_uploads = intval($DB->getColumn("SELECT count(*) FROM pre_file WHERE uid='{$uid}' AND addtime>='{$today0}'"));
$total_size = intval($DB->getColumn("SELECT IFNULL(SUM(size),0) FROM pre_file WHERE uid='{$uid}'"));

// 用户组与 API Key
$userRow = $DB->getRow("SELECT group_id, api_key FROM pre_user WHERE uid=:uid LIMIT 1", [':uid'=>$uid]);
$groupName = '';
if($userRow && isset($userRow['group_id'])){
    $g = $DB->getRow("SELECT name FROM pre_group WHERE id=:gid LIMIT 1", [':gid'=>$userRow['group_id']]);
    $groupName = $g ? $g['name'] : '';
}
$apiKey = $userRow && isset($userRow['api_key']) ? $userRow['api_key'] : '';

include './head.php';
?>

<style>
/* 自定义样式优化 */
.layui-card {
  border-radius: 2px;
  box-shadow: 0 1px 2px 0 rgba(0,0,0,0.05);
}

.layui-card-header {
  border-bottom: 1px solid #f6f6f6;
  font-weight: 600;
  color: #333;
}

.stat-card {
  transition: all 0.3s;
  border-left: 3px solid transparent;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.stat-card-files {
  border-left-color: #1E9FFF;
}

.stat-card-uploads {
  border-left-color: #5FB878;
}

.stat-card-size {
  border-left-color: #FFB800;
}

.stat-card-group {
  border-left-color: #FF5722;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin: 10px 0;
}

.stat-label {
  color: #666;
  font-size: 13px;
}

.api-input-group {
  display: flex;
}

.api-input-group .layui-input {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
  border-right: none;
}

.api-input-group .layui-btn {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

.key-message {
  margin-top: 15px;
  padding: 10px 15px;
  border-radius: 2px;
  background-color: #f8f8f8;
  border-left: 4px solid #5FB878;
}

.key-message.error {
  border-left-color: #FF5722;
}

.api-actions {
  margin-top: 20px;
}

.layui-icon {
  margin-right: 5px;
}

.card-icon {
  font-size: 24px;
  margin-right: 10px;
  color: #666;
}

.stat-card .layui-card-body {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-content {
  flex: 1;
}
</style>

<div class="layui-fluid">
  <div class="layui-row layui-col-space15">
    <!-- 数据概览卡片 -->
    <div class="layui-col-sm6 layui-col-md3">
      <div class="layui-card stat-card stat-card-files">
        <div class="layui-card-body">
          <i class="layui-icon card-icon">&#xe655;</i>
          <div class="stat-content">
            <div class="stat-value"><?= $total_files ?></div>
            <div class="stat-label">文件总数</div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="layui-col-sm6 layui-col-md3">
      <div class="layui-card stat-card stat-card-uploads">
        <div class="layui-card-body">
          <i class="layui-icon card-icon">&#xe67c;</i>
          <div class="stat-content">
            <div class="stat-value"><?= $today_uploads ?></div>
            <div class="stat-label">今日上传</div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="layui-col-sm6 layui-col-md3">
      <div class="layui-card stat-card stat-card-size">
        <div class="layui-card-body">
          <i class="layui-icon card-icon">&#xe857;</i>
          <div class="stat-content">
            <?php
              function fmtSize($bytes){
                $u=['B','KB','MB','GB','TB']; $i=0; $v=$bytes; while($v>1024 && $i<count($u)-1){ $v/=1024; $i++; }
                return round($v,2).' '.$u[$i];
              }
            ?>
            <div class="stat-value"><?= fmtSize($total_size) ?></div>
            <div class="stat-label">占用空间</div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="layui-col-sm6 layui-col-md3">
      <div class="layui-card stat-card stat-card-group">
        <div class="layui-card-body">
          <i class="layui-icon card-icon">&#xe770;</i>
          <div class="stat-content">
            <div class="stat-value"><?= $groupName ?: '未开通' ?></div>
            <div class="stat-label">用户组</div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- API Key 管理 -->
  <div class="layui-row">
    <div class="layui-col-xs12">
      <div class="layui-card">
        <div class="layui-card-header">
          <i class="layui-icon">&#xe672;</i> API Key 管理
        </div>
        <div class="layui-card-body">
          <div class="layui-form-item">
            <label class="layui-form-label">当前密钥</label>
            <div class="layui-input-block">
              <div class="api-input-group">
                <input type="text" id="api_key" class="layui-input" readonly value="<?= htmlspecialchars($apiKey) ?>" placeholder="暂无API Key">
                <button class="layui-btn layui-btn-normal" id="btnCopyKey"><i class="layui-icon">&#xe640;</i> 复制</button>
              </div>
            </div>
          </div>
          
          <div class="api-actions">
            <button class="layui-btn layui-btn-normal" id="btnGenKey"><i class="layui-icon">&#x1002;</i> 生成/重置密钥</button>
            <button class="layui-btn layui-btn-primary" id="btnShowHelp"><i class="layui-icon">&#xe607;</i> 使用帮助</button>
          </div>
          
          <div id="keyMsg" class="key-message" style="display: none;"></div>
        </div>
      </div>
    </div>
  </div>
</div>

<?php include './foot.php'; ?>
<script>
layui.use(['jquery','layer'], function(){
  var $ = layui.jquery, layer = layui.layer;
  
  // 复制密钥
  $('#btnCopyKey').on('click', function(){
    var v = $('#api_key').val();
    if(!v){ 
      layer.msg('当前密钥为空', {icon: 2}); 
      return; 
    }
    
    // 兼容性复制方法
    try {
      if(navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(v).then(function(){ 
          layer.msg('密钥已复制到剪贴板', {icon: 1}); 
        });
      } else {
        // 传统方法
        var $temp = $("<input>");
        $("body").append($temp);
        $temp.val(v).select();
        document.execCommand("copy");
        $temp.remove();
        layer.msg('密钥已复制到剪贴板', {icon: 1});
      }
    } catch (e) {
      layer.msg('复制失败，请手动复制', {icon: 2});
    }
  });
  
  // 生成/重置密钥
  $('#btnGenKey').on('click', function(){
    var ii = layer.msg('正在生成密钥...', {icon:16, time:0});
    $.ajax({
      type:'POST',
      url:'./ajax.php?act=api_key', 
      data: { 
        do:'genkey', 
        csrf_token: $('#csrf_token').val() 
      }, 
      dataType:'json'
    }).done(function(res){
      if(res.code===0){
        $('#api_key').val(res.api_key || '');
        $('#keyMsg').html('<i class="layui-icon layui-icon-ok"></i> API Key 生成成功！').show().removeClass('error');
        setTimeout(function() {
          $('#keyMsg').fadeOut();
        }, 3000);
      }else{
        $('#keyMsg').html('<i class="layui-icon layui-icon-close"></i> ' + (res.msg || '生成失败')).show().addClass('error');
      }
    }).fail(function(){
      $('#keyMsg').html('<i class="layui-icon layui-icon-close"></i> 网络错误，请重试').show().addClass('error');
    }).always(function(){ 
      layer.close(ii); 
    });
  });
  
  // 显示使用帮助
  $('#btnShowHelp').on('click', function(){
    layer.open({
      type: 1,
      title: '<i class="layui-icon">&#xe607;</i> API Key 使用帮助',
      area: ['600px', '400px'],
      shadeClose: true,
      content: '<div style="padding:20px;line-height:1.8;">' +
               '<h3 style="margin-bottom:15px;">API Key 用途</h3>' +
               '<p style="margin-bottom:15px;">API Key 用于通过编程方式访问您的账户，执行文件上传、管理等操作。</p>' +
               '<h3 style="margin-bottom:15px;">使用方式</h3>' +
               '<p style="margin-bottom:10px;">在API请求的Header中添加：</p>' +
               '<pre style="background:#f8f8f8;padding:10px;border-radius:2px;border-left:3px solid #1E9FFF;">Authorization: Bearer YOUR_API_KEY</pre>' +
               '<h3 style="margin-top:20px;margin-bottom:15px;">安全提示</h3>' +
               '<p>请妥善保管您的API Key，不要泄露给他人。如果怀疑密钥已泄露，请立即重置。</p>' +
               '</div>'
    });
  });
});
</script>